package com.tensquare.user.controller;

import com.tensquare.user.pojo.Admin;
import com.tensquare.user.service.AdminService;
import entity.Result;
import entity.StatusCode;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import util.JwtUtil;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by WF on 2020/4/3 14:52
 */
@RestController
@RequestMapping("admin")
public class AdminController {
    @Autowired
    private AdminService adminService;
    @Autowired
    private JwtUtil jwtUtil;
    @Autowired
    private HttpServletRequest request;
    //1.添加管理员
    @PostMapping("add")
    public Result add(@RequestBody Admin admin){
        //1.1)添加管理员
        adminService.add(admin);
        //1.2)返回
        return new Result(true,StatusCode.OK,"添加管理员成功！");
    }
    //2.管理员登录
    @PostMapping("login")
    public Result login(@RequestBody Admin admin){
        //2.1)根据登录用户的登录名查询用户是否存在
        Admin adminUser = adminService.login(admin);
        //2.2)判断是否存在
        if(adminUser != null){
            //2.2.1)用户登录成功后，就将登录信息写入jwt中
            String token = jwtUtil.createJWT(adminUser.getId(), adminUser.getLoginname(), "admin");
            //2.2.2)如果token有值，就放到map中
            if(StringUtils.isNotBlank(token)){
                Map map = new HashMap<>();
                map.put("token",token);
                map.put("loginname",adminUser.getLoginname());
                return new Result(true,StatusCode.OK,"登录成功！",map);
            }

        }
        return new Result(false,StatusCode.ERROR,"登录失败！");
    }
    //3.删除用户
    @DeleteMapping("{adminId}")
    public Result delete(@PathVariable String adminId){
        //3.1)从请求作用域中得到claims对象
        Claims claims = (Claims) request.getAttribute("claims");
        //3.2)判断是否为null
        if(claims != null){
            //3.2.1)得到角色
            String roles = (String) claims.get("roles");
            //3.2.2)如果是管理员，就可以执行删除
            if(StringUtils.isNotBlank(roles) && roles.equals("admin")){
                adminService.delete(adminId);
                return new Result(true,StatusCode.OK,"删除管理员成功！");
            }
        }
        return new Result(false,StatusCode.ERROR,"删除管理员失败！");
    }
}
